<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/1
 * Time: 16:41
 */
class LibTools
{
    /**
     * @param $url
     * @param int $code
     * @param string $default check不通过时，跳转地址
     */
    static public function redirect($url, $code = 302, $default = '/')
    {
        if ($code == 301) {
            header('HTTP/1.1 301 Moved Permanently');
        }

        header("location: {$url}");
        exit();
    }

    /**
     * 是否是cli模式下cron运行的脚本
     * @return bool
     */
    static public function isCliCronRun($argv)
    {
        if (php_sapi_name() == "cli" && isset($argv[2]) && $argv[2] == "cron") {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取本周的起始和结束时间
     * @param int $start
     * @return string
     */
    static public function getWeek($start = 1)
    {
        $date = new DateTime();
        $date->modify('this week');
        if ($start) {
            $time = $date->format('Y-m-d');
        } else {
            $date->modify('this week +6 days');
            $time = $date->format('Y-m-d');
        }
        return $time;
    }

    /**
     * 获取数组里面某个field的值的集合
     * @param $array
     * @param $field
     * @return array
     */
    static public function getArrField($array, $field)
    {
        $keys = [];
        foreach ($array as $arr) {
            if (isset($arr[$field])) {
                $keys[] = $arr[$field];
            }
        }
        return $keys;
    }

    /**
     * 获取客户端IP
     * @return string
     */
    static public function getIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
            $ip = getenv("REMOTE_ADDR");
        } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = "unknown";
        }
        return ($ip);
    }

    /**
     * 获取当前页面的完整的url
     * @return string
     */
    static public function getUrl()
    {
        return 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"];
    }
} 